package xyz.hlh.boot7.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.WeekendSqls;
import xyz.hlh.boot7.entity.User;
import xyz.hlh.boot7.mapper.UserMapper;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @author HLH
 * @description: UserController
 * @email 17703595860@163.com
 * @date : Created in 2021/10/19 15:42
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private UserMapper userMapper;

    @GetMapping("/1")
    public PageInfo<User> findAllUser() {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", Arrays.asList("1", "1"));
        example.orderBy("id").desc();
        PageHelper.startPage(0, 1);
        List<User> users = userMapper.selectByExample(example);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return pageInfo;
    }

    @GetMapping("/2")
    public PageInfo<User> findAllUser2() {
        Example example = Example.builder(User.class)
                .andWhere(WeekendSqls.<User>custom()
                        .andIn(User::getId, Arrays.asList(1, 2)))
                .orderByDesc("id")
                .build();
        PageHelper.startPage(0, 1);
        List<User> users = userMapper.selectByExample(example);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return pageInfo;
    }

    @PostMapping
    public User addUser(@RequestBody User user) {
        int flag = userMapper.insertSelective(user);
        if (flag > 0) {
            return user;
        }
        throw new RuntimeException("插入失败");
    }

    @PostMapping
    public User updateUser(@RequestBody User user) {
        if (user.getId() == null) {
            throw new RuntimeException("id为空，更新失败");
        }
        int flag = userMapper.updateByPrimaryKeySelective(user);
        if (flag > 0) {
            return user;
        }
        throw new RuntimeException("更新失败");
    }

    @DeleteMapping
    public void deleteUserById(Long id) {
        userMapper.deleteByPrimaryKey(id);
    }

}
